import { AxiosResponse, AxiosError } from 'axios'

type BaseRequest<T, V> = (params?: T) => Promise<AxiosResponse<V>>;

//成功状态约束
type SuccessResponse<V> = {
    code: 'success',
    data: V;
};

//失败状态约束
type ErrorResponse<E = AxiosError> = {
    code: 'error',
    error: E;
};
//基本状态约束
type BaseResponse<V, E> = Promise<SuccessResponse<V> | ErrorResponse<E>>;

export const requestHandler = <T, V, E = AxiosError>(
    request: BaseRequest<T, V>) => {
    return async (params?: T): BaseResponse<V, E> => {
        try {
            const response = await request(params);
            return {
                code: 'success',
                data: response.data
            };
        } catch (e) {
            return {
                code: 'error',
                error: e as E
            };
        }
    };
}